<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useShowLoginDialogStore } from '@/store/showLoginDiaolg';
import { useShowRegisterDialogStore } from '@/store/showRegisterDiaolg';
import { useShowSendEmailDialogStore } from '@/store/showSendEmailDiaolg';
import SendEmail from './SendEmail.vue';
import { userRegisterImageCheckCodeService, userSendRegisterEmailCheckCodeService, userRegisterService } from '@/api/user';
import axios from 'axios'
import verify from '@/utils/verify.js' // 导入正则校验工具类
import { getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance(); // 获取全局注册的组件

// 注册框store
const showRegisterDialogStore = useShowRegisterDialogStore();
// 登录框store
const showLoginDialogStore = useShowLoginDialogStore();
// 显示发送邮件框store
const showSendEmailDiaolgStore = useShowSendEmailDialogStore()

// 显示登录框
const showLoginDialog = () => {
  // 先关闭注册框
  showRegisterDialogStore.setShowRegisterDialog(false)
  // 再开启登录框
  showLoginDialogStore.setShowLoginDialog(true)
}

// 处理关闭用户注册框逻辑
const handleRegisterDialogClose = () => {
  showRegisterDialogStore.setShowRegisterDialog(false)
}

// 获取图片验证码
const imageCheckCodeUrl = ref()
const getImageCheckCode = async () => {
  // axios({
  //   url: '/api/user/user/getRegisterImageCheckCode',
  //   method: 'get',
  //   responseType: 'blob' //选择接收方式为blob
  // }).then((res) => {
  //   // console.log("res", res)
  //   imageCheckCodeUrl.value = URL.createObjectURL(res.data)
  // }).catch((err) => {
  //   // console.log("err", err)
  // })

  let res = await userRegisterImageCheckCodeService()
  imageCheckCodeUrl.value = URL.createObjectURL(res.data)
}

// 用户注册表单
const formDataRef = ref()
const formData = ref({
  password: 'ld123456',
  rePassword: 'ld123456',
  email: '1136749840@qq.com',
  emailCheckCode: '12345',
  imageCheckCode: 'vcgdq',
})
// 两次密码校验
const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.password) {
    callback(new Error(rule.message))
  } else {
    callback()
  }
}
// 校验规则
const rules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: 'blur' },
    { max: 150, message: "邮箱太长", trigger: 'blur' },
    { validator: verify.email, message: "请输入正确的邮箱", trigger: 'blur' }
  ],
  emailCheckCode: [{ required: true, message: "请输入邮箱验证码", trigger: 'blur' }],
  password: [
    { required: true, message: "请输入密码", trigger: 'blur' },
    { min: 6, message: "密码只能是字母、数字,长度为6-20位", trigger: 'blur' },
    { max: 20, message: "密码只能是字母、数字,长度为6-20位", trigger: 'blur' },
  ],
  rePassword: [
    { required: true, message: "请再次输入密码", trigger: 'blur' },
    { validator: checkRePassword, message: "两次输入的密码不一致", trigger: 'blur' }
  ],
  imageCheckCode: [{ required: true, message: "请输入图形验证码", trigger: 'blur' }],
}

// 显示注册框，禁止页面滚动，隐藏滚动条
const stopSrcoll = () => {
  console.log("Register页面 禁止页面滑动")
  let mo = function (e) { e.preventDefault(); };
  document.body.style.overflow = 'hidden';
  document.addEventListener("touchmove", mo, false); // 禁止页面滑动
}

// 关闭注册框，允许页面滚动，显示滚动条
const openSrcoll = () => {
  console.log("Register页面 出现滚动条")
  let mo = function (e) { e.preventDefault(); };
  document.body.style.overflow = ''; // 出现滚动条
  document.removeEventListener("touchmove", mo, false);
}

// 发送邮件验证码
const sendEmailCheckCode = async () => {
  let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
  let res = reg.test(formData.value.email)
  console.log("校验邮箱结果", res)

  if (res == false) {
    proxy.Notification.error('邮箱格式错误，请重新输入')
    getImageCheckCode()
    return
  }

  let result = await userSendRegisterEmailCheckCodeService({
    email: formData.value.email,
    imageCheckCode: formData.value.imageCheckCode
  })

  proxy.Notification.success(result.code === 1 ? '邮件验证码发送成功' : result.msg)
}

// 注册
const register = async () => {
  await formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }

    let result = await userRegisterService(formData.value)

    proxy.Notification.success(result.code === 1 ? '用户注册成功' : result.msg)

    // 注册成功后，关闭注册弹窗，并显示登录框
    showLoginDialog()
  })
}

onMounted(() => {
  // 获取图片验证码
  getImageCheckCode()
  // 禁止body滚动条
  stopSrcoll()
})

onUnmounted(() => {
  // 开启body滚动条
  openSrcoll()
})
</script>

<template>
  <!-- 用户注册 -->
  <div class="register-panel">
    <!-- 点击空白处不关闭 -->
    <el-dialog v-model="showRegisterDialogStore.showRegisterDialog" :close-on-click-modal="false"
      :close-on-press-escape="false" :before-close="handleRegisterDialogClose" @open="stopSrcoll()"
      @close="openSrcoll()">
      <div class="panel-title">云舟 - 注册</div>
      <div class="register-form">
        <!-- 表单 -->
        <el-form :model="formData" :rules="rules" ref="formDataRef" class="Register-form">
          <!-- 邮箱 -->
          <el-form-item prop="email">
            <el-input size="large" clearable placeholder="请输入邮箱" v-model="formData.email">
              <template #prefix>
                <span class="iconfont icon-email"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 邮箱验证码 -->
          <el-form-item prop="emailCheckCode">
            <div class="email-check-code-panel">
              <el-input size="large" clearable placeholder="请输入邮箱验证码" v-model="formData.emailCheckCode">
                <template #prefix>
                  <span class="iconfont icon-ziyuan"></span>
                </template>
              </el-input>
              <button type="button" class="send-email-check-code-button"
                @click.prevent="sendEmailCheckCode()">获取邮箱验证码</button>
            </div>
          </el-form-item>
          <!-- 用户密码 -->
          <el-form-item prop="password">
            <el-input size="large" clearable show-password placeholder="请输入密码" v-model="formData.password">
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 再次输入用户密码 -->
          <el-form-item prop="rePassword">
            <el-input size="large" clearable show-password placeholder="请再次输入密码" v-model="formData.rePassword">
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 注册 图形验证码 -->
          <el-form-item prop="imageCheckCode">
            <div class="image-check-code-panel">
              <el-input size="large" clearable placeholder="请输入图形验证码" v-model="formData.imageCheckCode">
                <template #prefix>
                  <span class="iconfont icon-check_code"></span>
                </template>
              </el-input>
              <img :src="imageCheckCodeUrl" class="image-check-code" @click="getImageCheckCode">
            </div>
          </el-form-item>
          <!-- 记住我、忘记密码、账号区 -->
          <!-- 注册用 -->
          <el-form-item>
            <div class="no-account">
              <a href="#" @click="showLoginDialog">已有账号？去登陆</a>
            </div>
          </el-form-item>
          <!-- 按钮区 -->
          <el-form-item>
            <button class="op-btn" @click.prevent="register()" type="button">注册</button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>

  <!-- 发送邮件框，需传入用户邮箱 -->
  <SendEmail v-if="showSendEmailDiaolgStore.showSendEmailDialog" :email="formData.email"></SendEmail>
</template>

<style>
.el-dialog__header {
  padding: 0px;
}

/* 修改注册框原css */
.el-dialog {
  width: 400px;
  border-radius: 5px;
}

/* 用户注册 */
.register-panel .panel-title {
  font-size: 20px;
  padding: 0px 10px 20px;
  color: #252933;
  border-bottom: 1px solid rgba(200, 202, 207, 0.5);
}

/* 注册表单 */
.register-panel .register-form {
  padding: 10px 5px 0px;
}

/* 邮箱验证码 */
.email-check-code-panel {
  width: 100%;
  display: flex;
  justify-content: space-between;

  /* 垂直居中 */
  align-items: center;
}

.email-check-code-panel .send-email-check-code-button {
  margin-left: 10px;
  width: 200px;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #fff;
  background-color: #67C23A;
  font-size: 14px;
  border: 0px;
}

/* 图形验证码区 */
.register-panel .register-form .image-check-code-panel {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.register-panel .register-form .image-check-code-panel img {
  margin-left: 10px;
  cursor: pointer;
}

/* 记住我区域 */
.register-panel .register-form .rememberme-panel {
  width: 100%;
}

/* 忘记密码、账号区域 */
.register-panel .register-form .no-account {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.register-panel .register-form .no-account a {
  border-bottom: 1px solid #fff;
}

.register-panel .register-form .no-account a:hover {
  border-bottom: 1px solid #000;
}

/* 按钮区 */
.register-panel .register-form .op-btn {
  width: 100%;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #fff;
  background-color: #67C23A;
  font-size: 16px;
  border: 0px;
}
</style>